package com.lson.classloader;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

public class MyClassLoader extends ClassLoader {
    public static void main(String[] args) {
        while(true){
            try {
                MyClassLoader myClassLoader = new MyClassLoader();
                Class<?> classes = myClassLoader.findClass("C:/work/SpringCloud/test/target/classes/com/lson/classloader/Person.class");
                Object o = classes.newInstance();
                Field field = classes.getDeclaredField("name");
                Object o1 = field.get(o);
                System.out.println(o1);

            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        File classFile = getClassFile(name);
        try {
            byte[] bytes = getClassBytes(classFile);
            Class<?> c = this.defineClass("com.lson.classloader.Person", bytes, 0, bytes.length);
            return c;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private File getClassFile(String name)
    {
        System.out.println("name"+name);
        File file = new File(name);
        return file;
    }
    private byte[] getClassBytes(File file) throws Exception
    {
        // 这里要读入.class的字节，因此要使用字节流
//        System.out.println(file.getAbsolutePath());
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel wbc = Channels.newChannel(baos);
        ByteBuffer by = ByteBuffer.allocate(1024);

        while (true)
        {
            int i = fc.read(by);
            if (i == 0 || i == -1)
                break;
            by.flip();
            wbc.write(by);
            by.clear();
        }

        fis.close();

        return baos.toByteArray();
    }
}
